<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="资产名称" prop="name" style="width: 200px;">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入资产名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="资产编号" prop="no" style="width: 200px;">
        <el-input
            v-model="queryParams.no"
            placeholder="请输入资产编号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="资产型号" prop="model" style="width: 200px;">
        <el-input
            v-model="queryParams.model"
            placeholder="请输入资产型号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="资产状态" prop="status" style="width: 210px;" >
        <el-select v-model="queryParams.status" placeholder="请选择资产状态" clearable >
          <el-option
              v-for="dict in assets_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" v-hasRole="['admin']">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['assets:assets:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['assets:assets:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['assets:assets:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['assets:assets:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="assetsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="资产ID" align="center" prop="id" />-->
      <el-table-column label="资产名称" align="center" prop="name" width="200"/>
      <el-table-column label="资产分类" align="center" prop="categoryName"/>
      <el-table-column label="资产编号" align="center" prop="no"/>
      <el-table-column label="资产图片" align="center" prop="img" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.img" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="资产型号" align="center" prop="model" width="200"/>
      <el-table-column label="数量" align="center" prop="num"/>
      <el-table-column label="购置日期" align="center" prop="date" width="100">
        <template #default="scope">
          <span>{{ parseTime(scope.row.date, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="初始价值" align="center" prop="money" width="200">
        <template #default="scope">
          <span>￥{{ scope.row.money.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="折旧方法" align="center" prop="depreciate"/>
      <el-table-column label="使用部门" align="center" prop="deptName"/>
      <el-table-column label="责任人" align="center" prop="userName"/>
      <el-table-column label="存放地点" align="center" prop="location"/>
      <el-table-column label="资产状态" align="center" prop="status">
        <template #default="scope">
          <!-- <dict-tag :options="assets_status" :value="scope.row.status"/>-->
          <el-tag type="primary" effect="dark" v-if="scope.row.status===0">正常</el-tag>
          <el-tag type="info" effect="dark" v-if="scope.row.status===1">停用</el-tag>
          <el-tag type="warning" effect="dark" v-if="scope.row.status===2">维修</el-tag>
          <el-tag type="danger" effect="dark" v-if="scope.row.status===3">报废</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="备注" align="center" prop="comment" width="300"/>
      <!--申请领用-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="150%">
        <template #default="scope">
          <el-button type="primary" dark="dark" icon="Edit" @click="handleReceive(scope.row.id)">申请领用
          </el-button>
        </template>
      </el-table-column>

      <el-table-column label="操作" v-hasRole="['admin']" align="center" class-name="small-padding fixed-width"  width="150%">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['assets:assets:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['assets:assets:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    <!-- 添加员工申请固定资产的对话框 -->
    <el-dialog title="申请领用" v-model="receiveVisible" width="500px" :close-on-click-modal="false" destroy-on-close>
      <el-form ref="receiveRef" :model="formReceive" :rules="receiveRules" label-width="80px">
        <el-form-item label="当还日期" prop="returnDate">
          <el-date-picker clearable
                          v-model="formReceive.returnDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择当还日期" style="width: 100%;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="comment">
          <el-input type="textarea" :rows="3" v-model="formReceive.comment" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFormReceive">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改资产详细信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="assetsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="资产名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入资产名称"/>
        </el-form-item>
        <el-form-item label="资产分类" prop="categoryName">
          <el-select style="width: 100%" v-model="form.categoryId">
            <el-option v-for="item in categoryList" :key="item.id" :value="item.id"
                       :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="资产编号" prop="no">
          <el-input v-model="form.no" placeholder="请输入资产编号"/>
        </el-form-item>
        <el-form-item label="资产图片" prop="img">
          <image-upload v-model="form.img"/>
        </el-form-item>
        <el-form-item label="资产型号" prop="model">
          <el-input v-model="form.model" placeholder="请输入资产型号"/>
        </el-form-item>
        <el-form-item label="数量" prop="num">
          <el-input-number :min="1" v-model="form.num" placeholder="请输入数量"/>
        </el-form-item>
        <el-form-item label="购置日期" prop="date">
          <el-date-picker clearable
                          v-model="form.date"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择购置日期" style="width: 100%;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="初始价值" prop="money">
          <el-input v-model="form.money" placeholder="请输入初始价值"/>
        </el-form-item>
        <el-form-item label="折旧方法" prop="depreciate">
          <!--<el-input v-model="form.depreciate" placeholder="请输入折旧方法说明" />-->
          <el-select style="width: 100%" v-model="form.depreciate">
            <el-option value="直线法"></el-option>
            <el-option value="工作量法"></el-option>
            <el-option value="算倍余额递减法"></el-option>
            <el-option value="年数总和法"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="使用部门" prop="deptId">
          <!--        <el-select v-model="form.deptId" ref="selectTrees" style="width: 100%" clearable >
                        <el-option
                                    v-for="item in deptList"
                                    :key="item.deptId"
                                    :value="item.deptId"
                                    :label="item.deptName"
                                    />
                                <el-tree :data="treeSelectList"
                                         :props="{children: 'children',label: 'label'}"
                                         highlight-current
                                         @node-click="handleNodeClick"
                                         default-expand-all/>
                              </el-select>-->

          <el-tree-select
              v-model="form.deptId"
              :data="treeSelectList"
              :props="{ value: 'id', label: 'label', children: 'children' }"
              clearable
              @check="nodeClick"
              default-expand-all
          >
          </el-tree-select>
          <!--          <el-input v-model="form.deptName" placeholder="请输入使用部门" />-->
        </el-form-item>
        <el-form-item label="责任人" prop="userName">
          <!--          <el-input v-model="form.userName" placeholder="请输入责任人" />-->
          <el-select style="width: 100%" v-model="form.userId">
            <el-option v-for="item in userNameList" :key="item.id" :value="item.userId"
                       :label="item.userName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="存放地点" prop="location">
          <el-input v-model="form.location" placeholder="请输入存放地点"/>
        </el-form-item>
        <el-form-item label="资产状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择资产状态" style="width: 100%;">
            <el-option
                v-for="dict in assets_status"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="comment">
          <el-input type="textarea" :rows="3" v-model="form.comment" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Assets">
import {listAssets, getAssets, delAssets, addAssets, updateAssets} from "@/api/assets/assets";
import {listCategory} from "@/api/category/category";
import {listUser} from "@/api/system/user";
import {treeselect} from "@/api/system/dept.js";
import useUserStore from '@/store/modules/user'
import {addReceive} from "@/api/receive/receive.js";


const {proxy} = getCurrentInstance();
const {assets_status} = proxy.useDict('assets_status');

const assetsList = ref([]);
const open = ref(false);
const receiveVisible = ref(false);
const receiveRef = ref(null);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const categoryList = ref([]);
const userNameList = ref([]);

const treeSelectList = ref([]);
// const deptList = ref([]);

const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const formReceive = reactive({
  assetsId: '',
  returnDate: '',
  comment: '',
});
const receiveRules = reactive({
  returnDate: [

  {
    validator: (rule, value) => {
      if (!value) return new Error('请选择当还日期');
      const selectedDate = new Date(value);
      const today = new Date();
      today.setHours(0, 0, 0, 0); // Set to start of day for comparison
      if (selectedDate < today) {
        return new Error('当还日期不能选择今天以前');
      }
      return true;
    },
    required: true,
    trigger: ['change', 'blur'],
  }]

});
const data = reactive({
      form: {},
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        no: null,
        model: null,
        status: null
      },
      rules: {
        name: [
          {required: true, message: "资产名称不能为空", trigger: "blur"}
        ],
        no: [
          {required: true, message: "资产编号不能为空", trigger: "blur"}
        ],
        model: [
          {required: true, message: "资产型号不能为空", trigger: "blur"}
        ],
        num: [
          {required: true, message: "数量不能为空", trigger: "blur"}
        ],
        money: [
          {required: true, message: "初始价值不能为空", trigger: "blur"}
        ],
        location: [
          {required: true, message: "存放地点不能为空", trigger: "blur"}
        ],
        status: [
          {required: true, message: "资产状态('在用', '闲置', '维修', '报废')不能为空", trigger: "change"}
        ],
      }
    }
);

const {queryParams, form, rules} = toRefs(data);


/** 查询资产详细信息列表 */
function getList() {
  loading.value = true;
  listAssets(queryParams.value).then(response => {
    assetsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function getAllList() {
  loading.value = true;
  listCategory().then(response => {
    categoryList.value = response.rows;
    loading.value = false;

  });
  listUser(null).then(response => {
    userNameList.value = response.rows;
    loading.value = false;
  });

  /*  listDept(queryParams.value).then(response => {
      deptList.value = response.data
      console.log("deptList.value", deptList.value)
      loading.value = false;
    });*/
  treeselect().then(response => {
    treeSelectList.value = response.data
    console.log("treeSelectList.value", treeSelectList.value)
    loading.value = false;
  });
}

const nodeClick = (data, node, vm) => {
  // 当前选中的节点
  //const checkedNode = node.checkedNodes[0];
  //console.log("nodeClick checkedNode", checkedNode);
  // 更新deptId
  form.value.deptId = data ? data.id : null;
};

// 员工申请领用物资的方法
function handleReceive(assetsId) {
  console.log("handleReceive assetsId", assetsId)
  receiveVisible.value=true;
  formReceive.assetsId=assetsId;
}
/*const submitFormReceive = () => {

  receiveRef.value.validate((valid) => {
    if (valid) {
      // 表单校验通过，执行提交逻辑
      console.log('Form is valid!');
    } else {
      console.log('Error submit!!');
      return false;
    }
  });
};*/

// 假设你已经从 Vuex 或其他地方获取了权限列表
const permissions = computed(() => {
  // 从 Vuex store 获取权限列表
  return useUserStore().permissions;
});

// 计算属性，检查是否显示操作列
const showOperationColumn = computed(() => {
  return permissions.value.includes('assets:assets:edit') ||
      permissions.value.includes('assets:assets:remove');
});

/**/
function submitFormReceive() {
  proxy.$refs["receiveRef"].validate(valid => {
    if (valid) {
      addReceive(formReceive)
          .then(response => {
            proxy.$modal.msgSuccess("待审核中");
            receiveVisible.value = false;
            receiveRef.value.resetFields();
            getList();
          })
          .catch(error => {
            // 处理错误情况
            proxy.$modal.msgError("领用申请失败了");
            console.error(error);
          });
    } else {
      // 当表单验证失败时，直接给出错误提示
      proxy.$modal.msgError("表单验证失败，请检查您的输入");
    }
  });
}




//-----------------------------
// 取消按钮
function cancel() {
  open.value = false;
  receiveVisible.value=false;
  receiveRefReset();
  reset();
}
function receiveRefReset() {
  formReceive.assetsId=null;
  formReceive.returnDate = null;
  formReceive.comment = null;
}
// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    categoryName: null,
    no: null,
    img: null,
    model: null,
    num: null,
    date: null,
    money: null,
    depreciate: null,
    deptName: null,
    userName: null,
    location: null,
    status: null,
    comment: null
  };
  proxy.resetForm("assetsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加资产详细信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getAssets(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改资产详细信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["assetsRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateAssets(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addAssets(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除资产详细信息编号为"' + _ids + '"的数据项？').then(function () {
    return delAssets(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('assets/assets/export', {
    ...queryParams.value
  }, `assets_${new Date().getTime()}.xlsx`)
}

getList();
getAllList();
</script>
